package com.zengdada.report.controller;

import com.zengdada.authority.annotation.SysLog;
import com.zengdada.authority.annotation.SysLogType;
import com.zengdada.authority.utils.JsonMessage;
import com.zengdada.report.service.JasperReportType;
import com.zengdada.report.service.ReportAuthorityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import static com.zengdada.authority.utils.JsonMessage.fail;
import static com.zengdada.authority.utils.JsonMessage.success;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2019/3/12 14:55
 * @Description:
 */
@Api(tags = "jasperReport 报表打印")
@Controller
@RequestMapping("/authority/jasper_report/")
public class JasperReportAuthorityController {

    @Autowired
    @Qualifier("reportAuthorityServiceImpl")
    ReportAuthorityService reportAuthorityService;

    @ApiOperation(value = "报表临时数据上传接口", notes = "可以先上传临时数据（只保留5分钟）)")
    @PostMapping("/save_temp_data.do")
    @ResponseBody
    public JsonMessage saveTempData(HttpServletRequest request) {
        try {
            return success((Object) reportAuthorityService.saveTempData(request));
        } catch (Exception e) {
            return fail("临时数据保存失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "报表打印接口", notes = "可以设置输出类型、打开方式(如果有其他参数不能直接通过api测试)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reportId", value = "报表ID(数据库（report_info）表ID，location设置绝对位置或者classpath相对位置)", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reportType", value = "报表输出类型（RTF、DOCX、XLSX、PDF）",allowableValues = "RTF,DOCX,XLSX,PDF", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isOpen", value = "报表是否使用浏览器打开（默认false）",allowableValues = "false,true", defaultValue = "false", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "tempDataId", value = "报表临时数据ID（可以通过save_temp_data.do请求提前上传数据，解决GET请求参数长度问题）", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = {"/report.do", "/report.html"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @SysLog(value = "报表打印", type = SysLogType.CONTROLLER)
    public void report(String reportId, String reportType, HttpServletRequest request, HttpServletResponse response) {
        boolean isOpen = "true".equals(request.getParameter("isOpen"));
        response.setCharacterEncoding("UTF-8");
//        response.setContentType(isOpen ? "text/plain;charset=UTF-8" : "application/force-download");
        response.setContentType("application/force-download");
        response.setHeader("Content-Transfer-Encoding", "binary");
        try (OutputStream out = response.getOutputStream()) {
            try {
                JasperReportType type;
                try {
                    type = JasperReportType.valueOf(reportType);
                } catch (Exception e) {
                    throw new NullPointerException("报表类型(reportType)未设置或者设置错误（仅支持：PDF、RTF、DOCX、XLSX）");
                }
                response.setHeader("Content-Disposition", String.format((isOpen ? "inline;" : "attachment;") + " filename=\"%s.%s\"", new String(reportId.getBytes(), StandardCharsets.UTF_8), type.name()));
                out.write(reportAuthorityService.report(reportId, request, type));
            } catch (Exception e) {
                String message = e.getMessage();
                response.setContentType("text/plain;charset=UTF-8");
                response.setHeader("Content-Disposition", String.format("inline; filename=\"%s.html\"", new String("出错了".getBytes(), StandardCharsets.UTF_8)));
                if (message != null) out.write(message.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
